package com.sfzd5;

import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import com.sfzd5.git.Repository;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

public class MainDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton 开始Button;
    private JButton 创建Button;
    private JLabel lb_msg;
    private JTable table_reps;
    private JButton 删除Button;
    private JButton 帮助Button;

    JGitHttpServer server;
    WTableModel dataModel;

    public MainDialog() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);


        try {
            server = new JGitHttpServer();

            dataModel = new WTableModel();
            table_reps.setModel(dataModel);
            table_reps.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) {
                        return;
                    }
                    int row = table_reps.getSelectedRow();
                    if (row != -1) {
                        Repository rep = server.getRepositoryList().repositories.get(row);
                        lb_msg.setText("http://127.0.0.1:" + server.getHttpServerPort() + "/" + rep.getMapping());
                    }
                }
            });

            开始Button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        //http://127.0.0.1:8080/hello
                        server.start();
                        lb_msg.setText("服务开启");
                    } catch (Exception exception) {
                        lb_msg.setText("服务启动出错");
                        exception.printStackTrace();
                        JOptionPane.showMessageDialog(null, exception.getMessage(), "启动服务出错", JOptionPane.ERROR_MESSAGE);
                    }

                }
            });

            创建Button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    CreateRepsository createRepsository = new CreateRepsository();

                    createRepsository.setTitle("创建仓库");
                    createRepsository.setPreferredSize(new Dimension(800, 600));
                    createRepsository.pack();

                    createRepsository.setModal(true);
                    createRepsository.setVisible(true);
                    Repository repository = createRepsository.getRepository();
                    if (repository != null) {
                        try {
                            org.eclipse.jgit.lib.Repository jRep = server.createRepository(repository);
                            dataModel.fireTableDataChanged();
                            lb_msg.setText("创建成功：" + repository.getName());
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                            lb_msg.setText("创建出错");
                        }
                    }
                }
            });

            删除Button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (table_reps.getSelectedRowCount() > 0) {
                        int sRowId = table_reps.getSelectedRow();
                        if (sRowId < 0)
                            return;
                        Repository rep = server.getRepositoryList().repositories.get(sRowId);
                        try {
                            server.deleteRepository(rep);
                            dataModel.fireTableDataChanged();
                            lb_msg.setText("删除完成");
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                            lb_msg.setText("删除出错");
                        }
                    } else {
                        lb_msg.setText("请选择要删除的仓库");
                    }
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
        帮助Button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(contentPane, server.printServerInfo(), "帮助", JOptionPane.INFORMATION_MESSAGE);
            }
        });
    }

    private void onOK() {
        close();
    }

    private void onCancel() {
        close();
    }

    private void close() {
        dispose();
        try {
            server.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MainDialog dialog = new MainDialog();
        dialog.setTitle("我的GIT服务器");
        dialog.setPreferredSize(new Dimension(800, 600));
        dialog.pack();
        dialog.setVisible(true);
        System.exit(0);
    }


    String[] columnNames = {"名称", "映射", "描述", "时间"};

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        contentPane = new JPanel();
        contentPane.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
        final JPanel panel1 = new JPanel();
        panel1.setLayout(new GridLayoutManager(1, 5, new Insets(0, 0, 0, 0), -1, -1));
        contentPane.add(panel1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
        final Spacer spacer1 = new Spacer();
        panel1.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
        final JPanel panel2 = new JPanel();
        panel2.setLayout(new GridLayoutManager(1, 3, new Insets(0, 0, 0, 0), -1, -1));
        panel1.add(panel2, new GridConstraints(0, 4, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        buttonOK = new JButton();
        buttonOK.setText("关闭");
        panel2.add(buttonOK, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        创建Button = new JButton();
        创建Button.setText("创建");
        panel2.add(创建Button, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        开始Button = new JButton();
        开始Button.setText("开始");
        panel2.add(开始Button, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        lb_msg = new JLabel();
        lb_msg.setText("信息");
        panel1.add(lb_msg, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        删除Button = new JButton();
        删除Button.setText("删除");
        panel1.add(删除Button, new GridConstraints(0, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        帮助Button = new JButton();
        帮助Button.setText("帮助");
        panel1.add(帮助Button, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final JPanel panel3 = new JPanel();
        panel3.setLayout(new BorderLayout(0, 0));
        contentPane.add(panel3, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        final JLabel label1 = new JLabel();
        label1.setText("仓库列表");
        panel3.add(label1, BorderLayout.NORTH);
        final JScrollPane scrollPane1 = new JScrollPane();
        panel3.add(scrollPane1, BorderLayout.CENTER);
        table_reps = new JTable();
        scrollPane1.setViewportView(table_reps);
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return contentPane;
    }

    class WTableModel extends AbstractTableModel {

        @Override
        public int getRowCount() {
            return server.getRepositoryList().repositories.size();
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Repository task = server.getRepositoryList().repositories.get(rowIndex);
            if (columnIndex == 0) {
                return task.getName();
            } else if (columnIndex == 1) {
                return task.getMapping();
            } else if (columnIndex == 2) {
                return task.getDescription();
            } else if (columnIndex == 3) {
                return task.getCreateDate().toString();
            }
            return "";
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
    }

}
